package com.opengw.beans.support;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class XMLValidator {
	
    private final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    private final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
    private Document document;
	
	public XMLValidator(byte[] content) throws ParserConfigurationException, SAXException, IOException{
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder parser = factory.newDocumentBuilder();
	    document = parser.parse(new ByteArrayInputStream(content));
	    ErrorHandler localSchemaErrorHandler = new LocalErrorHandler();      
        factory.setNamespaceAware(false);
        factory.setIgnoringComments(true);
        factory.setValidating(true);
        factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(localSchemaErrorHandler);
        document = builder.parse(new ByteArrayInputStream(content));
	}

	public String getDocumentString() throws IOException {
		OutputFormat format = new OutputFormat(document);
        format.setIndenting(true);
        
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        XMLSerializer serializer = new XMLSerializer(bout, format);
        serializer.serialize(document);
        
        return new String(bout.toByteArray());
	}
	
	class LocalErrorHandler implements ErrorHandler {
	    public void fatalError( SAXParseException e )
	       throws SAXException {
	      throw e;
	    }
	    public void error( SAXParseException e ) throws SAXException {
	    }
	    public void warning( SAXParseException e ) throws SAXException {
	    }
	  }
}
